package com.yuwei.common.view

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.SweepGradient
import android.graphics.Typeface
import android.util.AttributeSet
import android.view.View
import android.view.animation.LinearInterpolator
import com.yuwei.common.R

class CircleCountDownView @JvmOverloads constructor(context: Context,attributeSet: AttributeSet ?= null,defStyle : Int = 0):View(context,attributeSet,defStyle){
    private var mProcessBackgroundColor = Color.parseColor("#50000000")
    private var mProcessColor = Color.parseColor("#FFFFFF")
    private var mProcessWidth = 10f
    private var mTextColor = Color.parseColor("#FFFFFF")
    private var mTextSize = 20f
    private var countDownTime = 5
    private var centerX  = 0f
    private var centerY  = 0f
    private var radius  = 0f
    private var currentAngle = 0f
    private var remainingTime = countDownTime //剩余时间
    private lateinit var animator: ValueAnimator
    private var listener: OnCountDownFinishListener? = null

    //背景画笔对象
    private val backgroundPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE
        strokeWidth = mProcessWidth
        color = mProcessBackgroundColor
        strokeCap = Paint.Cap.ROUND
    }
    //进度画笔对象
    private val processPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE
        strokeWidth = mProcessWidth
        color = mProcessColor
        strokeCap = Paint.Cap.ROUND
        shader = SweepGradient(centerX,centerY, intArrayOf(Color.RED,Color.YELLOW,Color.GREEN),null)

    }
    //文字画笔对象
    private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = mTextColor
        textSize = mTextSize
        textAlign = Paint.Align.CENTER
        typeface = Typeface.DEFAULT_BOLD
    }

    /**
     * 读取xml文件的属性值
     */
    init {
        attributeSet?.let{
            context.obtainStyledAttributes(it, R.styleable.CircleCountdownView).apply {
                mProcessBackgroundColor = getColor(R.styleable.CircleCountdownView_progressBackgroundColor, mProcessBackgroundColor)
                mProcessColor = getColor(R.styleable.CircleCountdownView_progressColor, mProcessColor)
                mProcessWidth = getDimension(R.styleable.CircleCountdownView_progressWidth, mProcessWidth)
                mTextColor = getColor(R.styleable.CircleCountdownView_textColor, mTextColor)
                mTextSize = getDimension(R.styleable.CircleCountdownView_textSize, mTextSize)
                countDownTime = getInt(R.styleable.CircleCountdownView_countdownTime, countDownTime)
            }.recycle() //读取完成后必须释放 因为属于IO操作 不释放 容易导致内存泄露
     }
        //设置进度画笔样式
        backgroundPaint.strokeWidth = mProcessWidth
        processPaint.strokeWidth = mProcessWidth
        processPaint.color = mProcessColor
        textPaint.textSize = mTextSize
        textPaint.color = mTextColor
    }
    fun setOnCountDownFinishListener(listener: OnCountDownFinishListener){
        this.listener = listener
    }


    /**
     * 大小发生变化
     */
    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        centerX = w / 2f
        centerY = h / 2f
        radius = (w.coerceAtMost(h) - mProcessWidth) / 2f
    }
    //绘制UI
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.drawCircle(centerX,centerX,radius,backgroundPaint)
        val sweepAngle = 450 * (currentAngle/100f)
        canvas.drawArc(centerX-radius + mProcessWidth / 2,centerY-radius + mProcessWidth / 2,centerX+radius - mProcessWidth / 2,centerY+radius - mProcessWidth / 2,-90f,sweepAngle,false,processPaint)
        val textY = centerY - ((textPaint.descent() + textPaint.ascent()) / 2)
        canvas.drawText("跳过 ${remainingTime}s",centerX,textY,textPaint)
    }
    fun startCountDown(){
        animator = ValueAnimator.ofFloat(0f,100f).apply {
            duration = countDownTime * 1000L
            interpolator = LinearInterpolator()
            repeatCount = ValueAnimator.INFINITE
            repeatMode = ValueAnimator.RESTART
            addUpdateListener {
                currentAngle = it.animatedValue as Float
                //计算剩余时间
                remainingTime = (countDownTime-(currentAngle/100f)*countDownTime).toInt()
                if(remainingTime == 0 && listener != null){
                    listener?.onCountDownFinish()
                }
                //刷新UI
                invalidate()

            }
            start()
        }
    }
    fun cancelCountDown(){
        animator.cancel()
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        cancelCountDown()
    }
    interface OnCountDownFinishListener{
        fun onCountDownFinish()
    }
}